package com.thoughtworks.android.androsphere.service.c2dm;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class C2DMHttpRequestHelper {
    private static final String UTF8 = "UTF-8";
    private URLWrapper c2dmUrl;

    public C2DMHttpRequestHelper(URLWrapper c2dmUrl) {
        this.c2dmUrl = c2dmUrl;
    }

    public void execute(String authToken, Map<String, String> postDataMap, C2DMServiceResponseHandler handler) {
        StringBuilder postDataBuilder = new StringBuilder();
        try {
            for (String key : postDataMap.keySet()) {
                if (key.startsWith("data.")) {
                    postDataBuilder.append(key).append("=").
                        append(URLEncoder.encode(postDataMap.get(key), UTF8));
                } else {
                    postDataBuilder.append(key).append("=").append(postDataMap.get(key));
                }
                postDataBuilder.append("&");
            }

            byte[] postData = postDataBuilder.toString().getBytes(UTF8);

            HttpURLConnection conn = (HttpURLConnection) c2dmUrl.openConnection();

            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
            conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);

            OutputStream out = conn.getOutputStream();
            out.write(postData);
            out.close();

            int responseCode = conn.getResponseCode();
            handler.handle(responseCode, getResponseHeader(conn.getHeaderFields()), conn.getInputStream());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private Map<String, String> getResponseHeader(Map<String, List<String>> headerFields) {
        Map<String, String> headers = new HashMap<String, String>();
        for (String header : headerFields.keySet()) {
            StringBuffer headerValue = new StringBuffer();
            for (String string : headerFields.get(header)) {
                headerValue.append(string);
            }
            headers.put(header, headerValue.toString());
        }
        return headers;
    }
}
